<template>
  <div class="migrations-container">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <h2>数据库备份恢复</h2>
          <p>用于数据库备份和恢复，方便服务器迁移和数据保护</p>
        </div>
      </template>
      
      <el-tabs v-model="activeTab">
        <!-- 数据库备份 -->
        <el-tab-pane label="数据库备份" name="backup">
          <div class="backup-container">
            <el-alert
              title="数据库备份功能"
              type="info"
              description="生成完整的数据库SQL备份文件，包含所有表结构和数据。"
              show-icon
              :closable="false"
              style="margin-bottom: 20px;"
            />
            
            <div class="backup-actions">
              <el-button 
                type="primary" 
                size="large"
                @click="handleBackup" 
                :loading="backing"
                icon="Download"
              >
                {{ backing ? '正在生成备份...' : '生成数据库备份' }}
              </el-button>
            </div>
            
            <div class="backup-info" style="margin-top: 20px;">
              <el-descriptions title="备份说明" :column="1" border>
                <el-descriptions-item label="备份内容">完整数据库（表结构 + 数据）</el-descriptions-item>
                <el-descriptions-item label="备份格式">SQL文件</el-descriptions-item>
                <el-descriptions-item label="适用场景">服务器迁移、数据保护、系统恢复</el-descriptions-item>
                <el-descriptions-item label="文件大小">根据数据量而定，通常几MB到几十MB</el-descriptions-item>
              </el-descriptions>
            </div>
          </div>
        </el-tab-pane>
        
        <!-- 数据库恢复 -->
        <el-tab-pane label="数据库恢复" name="restore">
          <div class="restore-container">
            <el-alert
              title="数据库恢复功能"
              type="warning"
              description="从SQL备份文件恢复数据库，将完全替换当前数据库内容。请谨慎操作！"
              show-icon
              :closable="false"
              style="margin-bottom: 20px;"
            />
            
            <el-form label-width="120px">
              <el-form-item label="选择备份文件">
                <el-upload
                  ref="upload"
                  action=""
                  :auto-upload="false"
                  :limit="1"
                  :on-change="handleFileChange"
                  :file-list="fileList"
                  accept=".sql"
                >
                  <el-button type="primary" icon="Upload">选择SQL文件</el-button>
                  <template #tip>
                    <div class="el-upload__tip">
                      只支持 .sql 格式的备份文件，文件大小不超过 100MB
                    </div>
                  </template>
                </el-upload>
              </el-form-item>
              
              <el-form-item>
                <el-button 
                  type="danger" 
                  @click="handleRestore" 
                  :loading="restoring" 
                  :disabled="!fileList.length"
                  icon="Refresh"
                >
                  {{ restoring ? '正在恢复数据库...' : '开始恢复数据库' }}
                </el-button>
                <el-button @click="clearFile">清除文件</el-button>
              </el-form-item>
            </el-form>
            
            <el-alert
              title="重要提醒"
              type="error"
              :closable="false"
              style="margin-top: 20px;"
            >
              <ul style="margin: 0; padding-left: 20px;">
                <li>恢复操作将完全替换当前数据库内容</li>
                <li>建议在恢复前先生成当前数据库的备份</li>
                <li>恢复过程中请勿关闭页面或断开网络</li>
                <li>恢复完成后需要重新登录系统</li>
              </ul>
            </el-alert>
          </div>
        </el-tab-pane>
        
        <!-- 备份历史 -->
        <el-tab-pane label="备份历史" name="history">
          <div class="history-container">
            <div class="history-header">
              <h3>备份历史</h3>
              <el-button @click="fetchBackupHistory" icon="Refresh">刷新</el-button>
            </div>
            
            <el-table 
              :data="backupHistory" 
              style="width: 100%" 
              v-loading="loadingHistory"
              empty-text="暂无备份记录"
            >
              <el-table-column prop="fileName" label="文件名" min-width="200" />
              <el-table-column prop="fileSize" label="文件大小" width="120">
                <template #default="scope">
                  {{ formatFileSize(scope.row.fileSize) }}
                </template>
              </el-table-column>
              <el-table-column prop="createdAt" label="创建时间" width="180">
                <template #default="scope">
                  {{ formatDate(scope.row.createdAt) }}
                </template>
              </el-table-column>
              <el-table-column label="操作" width="200">
                <template #default="scope">
                  <el-button 
                    size="small" 
                    @click="downloadBackup(scope.row)"
                    :loading="downloading === scope.row.fileName"
                    icon="Download"
                  >
                    下载
                  </el-button>
                  <el-button 
                    size="small" 
                    type="danger" 
                    @click="deleteBackup(scope.row)"
                    :loading="deleting === scope.row.fileName"
                    icon="Delete"
                  >
                    删除
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-tab-pane>
      </el-tabs>
    </el-card>
  </div>
</template>

<script>
import { 
  backupDatabase, 
  restoreDatabase, 
  getBackupHistory, 
  downloadBackup as downloadBackupFile,
  deleteBackup as deleteBackupFile
} from '@/api/migration'

export default {
  name: 'MigrationsIndex',
  data() {
    return {
      activeTab: 'backup',
      backing: false,
      restoring: false,
      fileList: [],
      file: null,
      backupHistory: [],
      loadingHistory: false,
      downloading: null,
      deleting: null
    }
  },
  created() {
    if (this.activeTab === 'history') {
      this.fetchBackupHistory()
    }
  },
  watch: {
    activeTab(newVal) {
      if (newVal === 'history') {
        this.fetchBackupHistory()
      }
    }
  },
  methods: {
    // 生成数据库备份
    async handleBackup() {
      this.backing = true

      try {
        const response = await backupDatabase()

        if (response.data && response.data.status === 'success') {
          this.$message.success('数据库备份生成成功')

          // 自动下载备份文件
          const downloadUrl = response.data.data.downloadUrl
          const link = document.createElement('a')
          link.href = `${process.env.VUE_APP_API_BASE_URL || ''}${downloadUrl}`
          link.download = response.data.data.fileName
          document.body.appendChild(link)
          link.click()
          document.body.removeChild(link)

          // 刷新备份历史
          if (this.activeTab === 'history') {
            this.fetchBackupHistory()
          }
        } else {
          this.$message.error(response.data?.message || response.message || '备份生成失败')
        }
      } catch (error) {
        console.error('备份失败:', error)

        // 检查是否是超时错误
        if (error.code === 'ECONNABORTED' || error.message.includes('timeout')) {
          this.$message({
            message: '数据库备份操作超时，但可能仍在后台进行中。请稍后刷新页面检查结果。',
            type: 'warning',
            duration: 10000
          })
        } else if (error.response && error.response.data) {
          this.$message.error('备份生成失败: ' + (error.response.data.message || '未知错误'))
        } else {
          this.$message.error('备份生成失败: ' + (error.message || '网络错误'))
        }
      } finally {
        this.backing = false
      }
    },
    
    // 处理文件选择
    handleFileChange(file, fileList) {
      this.fileList = fileList
      this.file = file.raw
    },
    
    // 清除选择的文件
    clearFile() {
      this.fileList = []
      this.file = null
      this.$refs.upload.clearFiles()
    },

    // 恢复数据库
    async handleRestore() {
      if (!this.file) {
        this.$message.warning('请选择要恢复的SQL备份文件')
        return
      }

      // 二次确认
      const confirmed = await this.$confirm(
        '恢复操作将完全替换当前数据库内容，此操作不可逆！是否继续？',
        '危险操作确认',
        {
          confirmButtonText: '确定恢复',
          cancelButtonText: '取消',
          type: 'warning',
          confirmButtonClass: 'el-button--danger'
        }
      ).catch(() => false)

      if (!confirmed) return

      this.restoring = true

      try {
        const formData = new FormData()
        formData.append('file', this.file)

        const response = await restoreDatabase(formData)

        if (response.data && response.data.status === 'success') {
          this.$message.success('数据库恢复成功，请重新登录系统')

          // 清除文件选择
          this.clearFile()

          // 3秒后跳转到登录页
          setTimeout(() => {
            this.$router.push('/login')
          }, 3000)
        } else {
          this.$message.error(response.data?.message || response.message || '数据库恢复失败')
        }
      } catch (error) {
        console.error('恢复失败:', error)

        // 检查是否是超时错误
        if (error.code === 'ECONNABORTED' || error.message.includes('timeout')) {
          this.$message({
            message: '数据库恢复操作超时，但可能仍在后台进行中。请稍后刷新页面检查结果。',
            type: 'warning',
            duration: 10000
          })
        } else if (error.response && error.response.data) {
          this.$message.error('数据库恢复失败: ' + (error.response.data.message || '未知错误'))
        } else {
          this.$message.error('数据库恢复失败: ' + (error.message || '网络错误'))
        }
      } finally {
        this.restoring = false
      }
    },

    // 获取备份历史
    async fetchBackupHistory() {
      this.loadingHistory = true

      try {
        const response = await getBackupHistory()
        console.log('备份历史API响应:', response)
        console.log('备份历史API响应数据:', response.data)

        // axios响应结构：response.data 包含后端返回的数据
        if (response.data && response.data.status === 'success') {
          this.backupHistory = response.data.data || []
          console.log('设置备份历史数据:', this.backupHistory)
          console.log('备份历史数组长度:', this.backupHistory.length)
        } else {
          this.$message.error('获取备份历史失败')
        }
      } catch (error) {
        console.error('获取备份历史失败:', error)
        this.$message.error('获取备份历史失败')
      } finally {
        this.loadingHistory = false
      }
    },

    // 下载备份文件
    async downloadBackup(backup) {
      this.downloading = backup.fileName

      try {
        const link = document.createElement('a')
        link.href = backup.downloadUrl
        link.download = backup.fileName
        document.body.appendChild(link)
        link.click()
        document.body.removeChild(link)

        this.$message.success('开始下载备份文件')
      } catch (error) {
        console.error('下载失败:', error)
        this.$message.error('下载失败')
      } finally {
        this.downloading = null
      }
    },

    // 删除备份文件
    async deleteBackup(backup) {
      const confirmed = await this.$confirm(
        `确定要删除备份文件 "${backup.fileName}" 吗？`,
        '删除确认',
        {
          confirmButtonText: '确定删除',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch(() => false)

      if (!confirmed) return

      this.deleting = backup.fileName

      try {
        const response = await deleteBackupFile(backup.fileName)

        // 修复响应数据结构判断
        if (response.data && response.data.status === 'success') {
          this.$message.success('备份文件删除成功')
          this.fetchBackupHistory() // 刷新列表
        } else if (response.status === 'success') {
          // 兼容直接返回status的情况
          this.$message.success('备份文件删除成功')
          this.fetchBackupHistory() // 刷新列表
        } else {
          this.$message.error(response.data?.message || response.message || '删除失败')
        }
      } catch (error) {
        console.error('删除失败:', error)

        // 改进错误处理
        if (error.response && error.response.data) {
          this.$message.error('删除失败: ' + (error.response.data.message || '未知错误'))
        } else {
          this.$message.error('删除失败: ' + (error.message || '网络错误'))
        }

        // 即使出错也刷新列表，因为删除可能实际成功了
        this.fetchBackupHistory()
      } finally {
        this.deleting = null
      }
    },

    // 格式化文件大小
    formatFileSize(bytes) {
      if (bytes === 0) return '0 B'
      const k = 1024
      const sizes = ['B', 'KB', 'MB', 'GB']
      const i = Math.floor(Math.log(bytes) / Math.log(k))
      return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
    },

    // 格式化日期
    formatDate(dateString) {
      return new Date(dateString).toLocaleString('zh-CN')
    }
  }
}
</script>

<style scoped>
.migrations-container {
  padding: 20px;
}

.card-header h2 {
  margin: 0 0 8px 0;
  color: #303133;
}

.card-header p {
  margin: 0;
  color: #909399;
  font-size: 14px;
}

.backup-actions {
  text-align: center;
  padding: 40px 0;
}

.backup-actions .el-button {
  padding: 15px 30px;
  font-size: 16px;
}

.history-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.history-header h3 {
  margin: 0;
}

.el-upload__tip {
  color: #909399;
  font-size: 12px;
  margin-top: 5px;
}
</style>
